package org.nutz.easy.model;

import java.util.HashMap;
import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.easy.Record;
import org.nutz.lang.Strings;

/**
 * <p>实体持久化基类,如果一个应用出现多个数据库的情况下，如果pojo不属于default database,则必须重写setDatabase()方法，返回database.json中设置的库名</p>
 * @author defier Lai
 * <p>Date: 2009-9-30 下午10:35:59</p>
 * @version 1.0
 * @param <T>
 */
@SuppressWarnings("unchecked")
public class ActiveRecord<T> implements Record<T> {

	private Dao dao() {
		String database = getDatabase();
		return EasyDataSource.get(database);
	}

	public String getDatabase() {
		return null;
	}
	
	@Override
	public void save() {
		dao().insert(this);
	}
	
	@Override
	public T find(Long id) {
		return (T) dao().fetch(this.getClass(), id);
	}
	
	@Override
	public T findFirst(String condition) {
		return (T) dao().fetch(this.getClass(), Cnd.wrap(condition));
	}

	@Override
	public T find(String name) {
		return (T) dao().fetch(this.getClass(), name);
	}

	@Override
	public List<T> findAll(String condition) {
		return (List<T>) dao().query(this.getClass(), Cnd.wrap(condition), null);
	}
	
	@Override
	public List<T> findAll() {
		return (List<T>) dao().query(this.getClass(), null, null);
	}

	@Override
	public void deleteAll() {
		dao().clear(this.getClass());
	}

	@Override
	public void delete(Long id) {
		dao().delete(this.getClass(), id);
	}
	
	@Override
	public void delete(String name) {
		dao().delete(this.getClass(), name);
	}

	@Override
	public void update() {
		dao().update(this);
	}

	@Override
	public List<T> findAll(HashMap<String, String> condition) {
		String str = setCondition(condition);
		return (List<T>) dao().query(this.getClass(), Cnd.wrap(str), null);
	}

	@Override
	public List<T> findBySql(String sql) {
		return null;
	}

	@Override
	public T findFirst(HashMap<String, String> condition) {
		String str = setCondition(condition);
		return (T) dao().fetch(this.getClass(), Cnd.wrap(str));
	}
	
	private String setCondition(HashMap<String, String> condition) {
		StringBuilder sb = new StringBuilder();
		String where = condition.get(WHERE);
		String order = condition.get(ORDER);
		String group = condition.get(GROUP);
		String limit = condition.get(LIMIT);
		if(!Strings.isEmpty(where)) {
			sb.append(where + " ");
		}
		if(!Strings.isEmpty(order)) {
			sb.append(order + " ");
		}
		if(!Strings.isEmpty(group)) {
			sb.append(group + " ");
		}
		if(!Strings.isEmpty(limit)) {
			sb.append(limit + " ");
		}
		return sb.toString();
	}
}
